<template>
  <div v-loading="state.loading" class="tree-box">
    <el-tree
      ref="treeEl"
      class="tree"
      highlight-current
      default-expand-all
      :data="props.api ? state.list : props.list"
      :props="{ label: props.label, children: props.childrenKey }"
      @node-click="handleNodeClick"
      v-bind="$attrs"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { type TreeInstance } from 'element-plus'
  import request from '@/service'
  import { Ui } from '@/utils'

  interface IEmits {
    (e: 'refactor-list', list: any[]): void
    (e: 'node-click', data: any): void
  }

  const emits = defineEmits<IEmits>()

  const props = defineProps({
    api: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    },
    childrenKey: {
      type: String,
      default: 'children'
    },
    label: {
      type: String,
      default: 'label'
    }
  })

  const treeEl = ref<TreeInstance>()

  const state = reactive({
    loading: false,
    list: []
  })

  /**----------------------------methods----------------------------------------------------------------------- */

  const handleNodeClick = (node: any, TreeNodeArr: any, TreeNode: any) => {
    emits('node-click', {
      node,
      TreeNodeArr,
      TreeNode
    })
  }

  const query = () => {
    const { api } = props
    if (!api) return

    state.loading = true

    request
      .get(api)
      .then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)
        emits('refactor-list', res.data)
        state.list = res.data
      })
      .finally(() => (state.loading = false))
  }

  const setCurrentKey = (key: string, expand = true) => {
    treeEl.value?.setCurrentKey(key, expand)
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */

  query()

  defineExpose({
    setCurrentKey
  })
</script>

<style scoped lang="less">
  .tree {
    width: 250px;
  }
  :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
    background-color: #3e72eb;
    color: #fff;
    border-radius: 4px;
    height: 32px;
  }
</style>
